<?php
session_start();
include "../php/common.php";
try {

	$rawpostdata = file_get_contents("php://input");
	//	var_dump($rawpostdata);
	$post = json_decode($rawpostdata, true);
	//var_dump($post);
	//	array (size=5)  'jiaoshi_id' => string '68' (length=2)
	//	 'occupy' => int 1  'the_usage' => string 'hbdddddddddddfhdfhfd' (length=20)  '
	//	 tips' => string '123456' (length=6)  'date' => string '2014-02-09' (length=10)
	// if (count($post) != 6)
		// die(json_encode(array("state" => "error", "msg" => "指令错误1")));
	if (isset($_SESSION['isLogin']) != true || $_SESSION['isLogin'] != true)
		die(json_encode(array("state" => "error", "msg" => "你没有登录")));
	if (preg_match('/\d{4}-\d{2}-\d{2}/', $post['date']) != 1)
		die(json_encode(array("state" => "error", "msg" => "指令错误2")));

	$post["jiaoshi_id"] = intval($post["jiaoshi_id"]);

	$pre = array($post["date"], $post["jiaoshi_id"], $post['occupy']);
	$sql = "SELECT * FROM `state` where `date` = ? and `jiaoshi_id` = ? and `occupy` = ?  ";
	$re = pdoGet($sql, $pre);
	$addMsg = "增加成功";
	if (count($re) != 0) {
		$re = $re[0];
		//		var_dump($re);
		if ($re['username'] == $_SESSION['username']) {
			$sql = "DELETE  FROM `state` where `date` = ? and `jiaoshi_id` = ? and `occupy` = ?";
			$pre = array($post["date"], $post["jiaoshi_id"],$post['occupy']);
			//			var_dump($pre);
			$re = pdoGet($sql, $pre);
			if ($post['todo'] == "del") {
				die(json_encode(array("state" => "success", "msg" => "删除成功")));
			}
		} else {
			die(json_encode(array("state" => "error", "msg" => "你没有权限")));
		}
		$addMsg = "修改成功";
	}
	if ($post['todo'] == "save") {
		$sql = "SELECT * FROM `jiaoshi` WHERE `jiaoshi_id` = ?";
		$pre = array($post['jiaoshi_id']);
		$re = pdoGet($sql, $pre);
		$post['jiaoxuelou_id'] = $re[0]['jiaoxuelou_id'];

		$sql = "INSERT INTO `ms`.`state` (`id`, `date`, `jiaoxuelou_id`, `jiaoshi_id`, `occupy`, `username`, `usernick`, `the_usage`, `tips`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?) ";
		$pre = array($post['date'], $post['jiaoxuelou_id'], $post['jiaoshi_id'], $post['occupy'], $_SESSION['username'], $_SESSION['nickname'], $post['the_usage'], $post['tips']);
		$re = pdoGet($sql, $pre);
		die(json_encode(array("state" => "success", "msg" => $addMsg)));
	}

} catch(Exception $e) {

	die(json_encode(array("state" => "error", "msg" => "未知错误")));
}
?>

